package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author 孤风雪影
 * @date 2021/1/17
 */
@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token) {
        String userInfo = stringRedisTemplate.opsForValue().get(token);
        return userInfo;
    }

    /**
     * 认证服务器登录页
     *
     * @param redirect_url
     * @param model
     * @param sso_token
     * @return
     */
    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String redirect_url,
                            @CookieValue(value = "sso_token", required = false) String sso_token,
                            Model model) {

        //有Cookie，之前登陆过
        if (!StringUtils.isEmpty(sso_token)) {
            return "redirect:" + redirect_url + "?token=" + sso_token;
        }

        //没有登陆过，返回登录页
        model.addAttribute("redirect_url", redirect_url);
        return "login";
    }


    /**
     * 处理登录请求
     *
     * @param username
     * @param password
     * @param redirect_url
     * @param response
     * @return
     */
    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("redirect_url") String redirect_url,
                          HttpServletResponse response) {

        // 只要账号密码不为空，就默认登录成功
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {

            //把登录成功的用户保存起来
            String uuid = UUID.randomUUID().toString().replace("-", "");
            stringRedisTemplate.opsForValue().set(uuid, username);

            //给认证服务器，添加cookie
            Cookie sso_token = new Cookie("sso_token", uuid);
            response.addCookie(sso_token);

            //登录成功,跳回之前页面
            return "redirect:" + redirect_url + "?token=" + uuid;
        }

        //登录失败,展示登录页
        return "login";
    }
}
